package com.youngball.web.controller.sys.web.controller;


import com.youngball.business.exception.MyDefineException;
import com.youngball.business.utill.Code;
import com.youngball.business.utill.ObjectNullUtils;
import com.youngball.shiro.entity.Role;
import com.youngball.shiro.entity.User;
import com.youngball.shiro.service.OrganizationService;
import com.youngball.shiro.service.ResourceService;
import com.youngball.shiro.service.RoleService;
import com.youngball.shiro.service.UserService;
import com.youngball.web.controller.BaseController;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;



/**

 */
@Controller
@RequestMapping("${adminPath}/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    @RequiresPermissions("user:view")
    @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json",value = "/users")
    @ResponseBody
    public Map list(Model model) {
        Map maps=new HashMap();
        maps.put("msg",userService.findAll());
        return maps;
    }

    @RequestMapping(value = "showUsers",method = RequestMethod.GET)
    public ResponseEntity<Map> showUsers() {
        Map maps = new HashMap();
        try
        {
            List<User> users = userService.findAll();
            for(User user : users)
            {
                StringBuffer buffer = new StringBuffer();
                List<Long> roles = user.getRoleIds();
                for(Long role : roles)
                {
                    if(buffer.length() > 0) buffer.append(",");
                    Role one = roleService.findOne(role);
                    if(ObjectNullUtils.isNotBlank(one)) {
                        buffer.append(one.getRole());
                    }
                }
                user.setRoleStr(buffer.toString());
            }

            maps.put("code","0");
            maps.put("msg", "获取成功");
            maps.put("data",users);
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "showUserWareHouse",method = RequestMethod.GET)
    public ResponseEntity<Map> showUserWareHouse(Long id) {
        Map maps = new HashMap();
        try
        {
            String name = null;
            User users = userService.findOne(id);
            maps.put("code","0");
            maps.put("msg", "获取成功");
            maps.put("data",users);
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequiresPermissions("user:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        setCommonData(model);
        model.addAttribute("user", new User());
        model.addAttribute("op", "新增");
        return "user/edit";
    }

    @RequiresPermissions("user:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(User user, RedirectAttributes redirectAttributes) {
        userService.createUser(user);
        redirectAttributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/user";
    }

    @RequestMapping(value = "createUsers",method = RequestMethod.POST)
    public ResponseEntity<Map> createUsers(@RequestBody User user) {
        Map maps = new HashMap();
        try
        {
            if(isAdmin(user))
            {
                maps.put("msg", "不能新增成为系统管理员");
                maps.put("code", Code.DEFAI.toString());
                return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
            }

            userService.createUser(user);
            maps.put("code","0");
            maps.put("msg", "新增成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "操作失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequiresPermissions("user:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute("user", userService.findOne(id));
        model.addAttribute("op", "修改");
        return "user/edit";
    }

    @RequiresPermissions("user:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(User user, RedirectAttributes redirectAttributes) {
        userService.updateUser(user);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/user";
    }

    boolean isAdmin(User user)
    {
        List<Long> roles = user.getRoleIds();
        if(roles == null) return false;

        for(Long roleId : roles)
        {
            Role role = roleService.findOne(roleId);
            if (role.getRole().equals("admin")) return true;
        }

        return false;
    }

    @RequestMapping(value = "updateUsers",method = RequestMethod.POST)
    public ResponseEntity<Map> updateUsers(@RequestBody User user) {
        Map maps = new HashMap();
        try
        {
            User local = userService.findOne(user.getId());
            if(isAdmin(local))
            {
                maps.put("msg", "不能修改系统管理员信息");
                maps.put("code", Code.DEFAI.toString());
                return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
            }

            if(isAdmin(user))
            {
                maps.put("msg", "不能修改成为系统管理员");
                maps.put("code", Code.DEFAI.toString());
                return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
            }

            if(user.getUsername()!=null && !user.getUsername().equals(local.getUsername())){
                User user1 =userService.findByMyUsername(user.getUsername());
                if(ObjectNullUtils.isNotBlank(user1)){
                    maps.put("msg", "已存在相同名字的用户");
                    maps.put("code", Code.DEFAI.toString());
                    return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
                }
            }

            if(user.getOrganizationId() != null) local.setOrganizationId(user.getOrganizationId());
            if(user.getUsername() != null) local.setUsername(user.getUsername());
            if(user.getRoleIds() != null && user.getRoleIds().size() > 0) local.setRoleIds(user.getRoleIds());
            userService.updateUser(local);
            maps.put("code","0");
            maps.put("msg", "修改成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute("user", userService.findOne(id));
        model.addAttribute("op", "删除");
        return "user/edit";
    }

    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        userService.deleteUser(id);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/user";
    }

    @RequestMapping(value = "deleteUsers/{id}",method = RequestMethod.POST)
    public ResponseEntity<Map> deleteUsers(@PathVariable Long id) {
        Map maps = new HashMap();
        try
        {
            User local = userService.findOne(id);
            if(isAdmin(local))
            {
                maps.put("msg", "不能删除系统管理员");
                maps.put("code", Code.DEFAI.toString());
                return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
            }

            userService.deleteUser(id);
            maps.put("code","0");
            maps.put("msg", "删除成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }
    @RequiresPermissions("user:update")
    @RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
    public String showChangePasswordForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("user", userService.findOne(id));
        model.addAttribute("op", "修改密码");
        return "user/changePassword";
    }


    @RequestMapping(value = "changePassword", method = RequestMethod.POST)
    public ResponseEntity<Map> changePassword(@RequestBody User user) {
        Map maps=new HashMap();
        try {
            userService.changePassword(user.getId(), user.getNewPassword(),user.getOldPassword());
            maps.put("code",Code.SUC.toString());
            maps.put("msg","修改密码成功");

        }catch (MyDefineException e){
            maps.put("code",Code.DEFAI.toString());
            maps.put("msg",e.getMessage());
        }  catch (Exception e){
            maps.put("code",Code.DEFAI.toString());
            maps.put("msg","修改密码失败");
        }
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "resetPassword", method = RequestMethod.POST)
    public ResponseEntity<Map> resetPassword(@RequestBody User user) {
        Map maps=new HashMap();
        try {
            userService.resetPassword(user.getId(), user.getNewPassword());
            maps.put("code",Code.SUC.toString());
            maps.put("msg","修改密码成功");

        }catch (MyDefineException e){
            maps.put("code",Code.DEFAI.toString());
            maps.put("msg",e.getMessage());
        }  catch (Exception e){
            maps.put("code",Code.DEFAI.toString());
            maps.put("msg","修改密码失败");
        }
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<Map> findUser() {
        List<User> users= userService.findAllUser();
        Map maps=new HashMap();
        maps.put("data", users);
        maps.put("code", Code.SUC.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);

    }

    private void setCommonData(Model model) {
        model.addAttribute("organizationList", organizationService.findAll());
        model.addAttribute("roleList", roleService.findAll());
    }

    @RequestMapping(value = "verifyUser", method = RequestMethod.POST)
    public ResponseEntity<Map> verifyUser(@RequestBody User user) {
        Map maps=new HashMap();
        if(user.getUsername() == null || user.getPassword() == null)
        {
            maps.put("msg","请输入授权用户名密码");
            maps.put("code","1");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }

        User local= userService.findByUsername(user.getUsername());
        if(local == null)
        {
            maps.put("msg","用户不存在");
            maps.put("code","1");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }

        User user1 = new User();
        try {
            BeanUtils.copyProperties(user1, local);
            user1.setPassword(user.getPassword());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        user = userService.getEncodeUser(user1);
        if(!local.getPassword().equals(user.getPassword()))
        {
            maps.put("msg","密码不正确");
            maps.put("code","1");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }

        boolean result = false;
        Set<String> permisions = userService.findMyPermissions(local.getUsername());
        for(String permision : permisions)
        {
            if(permision.contains("goods:discount"))
            {
                result = true;
            }
        }
/*
        List<Long> roleList = local.getRoleIds();
        for(Long longId : roleList)
        {
            Role role = roleService.findOne(longId);
            List<Long> resources = role.getResourceIds();
            for(Long resourceId : resources)
            {
                com.syg.sys.entity.Resource resource = resourceService.findOne(resourceId);
                if(resource.getPermission().equals("goods:discount"))
                {
                    result = true;
                    break;
                }
            }
        }
*/
        if(result)
        {
            maps.put("msg","验证成功");
            maps.put("code","0");
        }
        else
        {
            maps.put("msg","该用户没有权限");
            maps.put("code","1");
        }

        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }
}
